package cloud.seri.gateway.web.filter

import cloud.seri.gateway.security.oauth2.OAuth2AuthenticationService

import org.springframework.security.config.annotation.SecurityConfigurerAdapter
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter
import org.springframework.security.oauth2.provider.token.TokenStore
import org.springframework.security.web.DefaultSecurityFilterChain

/**
 * Configures a [RefreshTokenFilter] to refresh access tokens if they are about to expire.
 *
 * @see RefreshTokenFilter
 */
class RefreshTokenFilterConfigurer(
    /**
     * [RefreshTokenFilter] needs the [OAuth2AuthenticationService] to refresh cookies using the refresh token.
     */
    private val authenticationService: OAuth2AuthenticationService,
    private val tokenStore: TokenStore
) : SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>() {

    /**
     * Install [RefreshTokenFilter] as a servlet Filter.
     */
    @Throws(Exception::class)
    override fun configure(http: HttpSecurity) {
        val customFilter = RefreshTokenFilter(authenticationService, tokenStore)
        http.addFilterBefore(customFilter, OAuth2AuthenticationProcessingFilter::class.java)
    }
}
